<template>
  <!-- 弹窗遮罩 -->
  <div v-if="visible" class="modal-mask" @click.self="closeModal">
    <div class="modal-container">
      <h3>选择目录</h3>
      <div class="dir-list">
        <div v-for="(dir, index) in directories" :key="index" class="dir-item">
          <input
            type="checkbox"
            :id="'dir-' + index"
            :value="dir"
            :checked="isSelected(dir)"
            @change="toggleDir(dir)"
          />
          <label :for="'dir-' + index">{{ dir }}</label>
        </div>
      </div>
      <div v-for="(c, i) in command" :key="i" class="command-item">
        <label :for="'command-' + i">{{ c }}</label>
      </div>
      <div>
        <input v-model="cron" placeholder="Cron表达式" />
        {{ cron }}
      </div>
      <div class="modal-actions">
        <button @click="closeModal">取消</button>
        <button @click="confirm">确认</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, onMounted, watch } from 'vue'
import CronPicker from './CronPicker.vue'
import { GitCommand } from '../js/enum/GitCommand'

const props = defineProps({
  visible: Boolean,
  directories: Array,
  selectedDirs: Array
})

const emit = defineEmits(['confirm', 'update:visible']) // 注意这里！

const sendSelectedDirs = ref([...props.selectedDirs])
watch(
  () => props.selectedDirs,
  (newVal) => {
    sendSelectedDirs.value = [...newVal]
  }
)

const cron = ref('')

const command = []

const confirm = () => {
  emit('confirm', sendSelectedDirs.value)
  closeModal()
}

// 修复：关闭弹窗并通知父组件更新 visible 状态
const closeModal = () => {
  sendSelectedDirs.value = []
  emit('update:visible', false)
}

// 检查目录是否已被选中
const isSelected = (dir) => {
  return sendSelectedDirs.value.includes(dir)
}

// 切换目录选中状态
const toggleDir = (dir) => {
  const index = sendSelectedDirs.value.indexOf(dir)
  if (index === -1) {
    sendSelectedDirs.value.push(dir) // 未选中 -> 选中
  } else {
    sendSelectedDirs.value.splice(index, 1) // 已选中 -> 取消
  }
}

onMounted(() => {
  command.push(GitCommand.pull.command, GitCommand.commitPush.command)
})
</script>

<style scoped>
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.modal-container {
  background: #4c4444;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  max-height: 80vh;
  overflow-y: auto;
}
.dir-list {
  margin: 15px 0;
}
.dir-item {
  padding: 8px 0;
  border-bottom: 1px solid #d15e5e;
}
.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
